package com.timeriver.config;

import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * http客户端服务：基于 livy 进行 Spark 任务的提交
 * 单例模式创建httpclient连接池对象
 */
@Configuration
public class RestTemplateConfig {

    private RestTemplateConfig() {
        super();
    }

    private static class Holder {

        private static final HttpComponentsClientHttpRequestFactory HTTP_REQUEST_FACTORY;

        static {
            // TODO 后续将参数改为可配置项
            /** 使用httpclient连接池 */
            HTTP_REQUEST_FACTORY = new HttpComponentsClientHttpRequestFactory(
                    HttpClientBuilder.create()
                                     /** httpclient连接池最大连接数 */
                                     .setMaxConnTotal(20)
                                     /** 单个路由的最大连接数 */
                                     .setMaxConnPerRoute(10)
                                     .build());
            HTTP_REQUEST_FACTORY.setConnectionRequestTimeout(3000);
            HTTP_REQUEST_FACTORY.setConnectTimeout(5000);
            HTTP_REQUEST_FACTORY.setReadTimeout(5000);
        }
    }

    @Bean(name = "restTemplate")
    public RestTemplate initRestTemplate() {
        return new RestTemplate(Holder.HTTP_REQUEST_FACTORY);
    }
}
